package com.feiyisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feiyisys.bo.UpdateVideoStatusBO;
import com.feiyisys.dto.FindVPageDTO;
import com.feiyisys.dto.UpdateVideoDTO;
import com.feiyisys.entity.Category;
import com.feiyisys.manager.AsyncVideoUploadManager;
import com.feiyisys.entity.Video;
import com.feiyisys.mapper.VideoMapper;
import com.feiyisys.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feiyisys.utils.TencentVodUtil;
import com.qcloud.vod.model.VodUploadResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 文化遗产相关视频表 服务实现类
 * </p>
 *
 * @author wq
 * @since 2025-10-10
 */
@Service
@Slf4j
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Resource
    private AsyncVideoUploadManager asyncUploadManager;

    @Resource
    private TencentVodUtil tencentVodUtil;

    /**
     * 上传视频服务方法
     */
    /**
     * 上传视频服务方法（自动分片）
     */
//    public VodUploadResponse uploadVideo(MultipartFile videoFile, MultipartFile coverFile,
//                                         String title, String description) {
//        try {
//            // 执行上传（自动分片）
//            VodUploadResponse vodUploadResponse = tencentVodUtil.uploadVideo(videoFile, coverFile);
//
//            // 保存到数据库
//            Video video = new Video();
//            video.setVideoUrl(vodUploadResponse.getMediaUrl());
//            video.setCoverImage(vodUploadResponse.getCoverUrl());
//            video.setId(Long.valueOf(vodUploadResponse.getFileId()));
//            video.setTitle(title);
//            video.setDescription(description);
//            this.save(video);
//            return vodUploadResponse;
//
//        } catch (Exception e) {
//            log.error("视频上传失败，文件名: {}", videoFile.getOriginalFilename(), e);
//            throw new RuntimeException("视频上传失败: " + e.getMessage());
//        }
//    }



    /**
     * 异步上传
     */
    public String asyncUploadVideo(MultipartFile videoFile, MultipartFile coverFile,
                                   String title, String description) {
        try {
            Video video = new Video();
            Long vId = saveVideoInfo(video, title, description);
            // 提交异步任务
            String taskId = asyncUploadManager.submitUploadTask(videoFile, coverFile);
            log.info("1视频id是: {}", vId);
            // 异步保存视频信息（当上传完成后）
            CompletableFuture.runAsync(() -> {
                try {
                    // 等待上传完成
                    waitForUploadCompletion(taskId);

                    // 获取上传结果并保存
                    AsyncVideoUploadManager.UploadTask task = asyncUploadManager.getTaskStatus(taskId);
                    if (task.getStatus() == AsyncVideoUploadManager.UploadTask.UploadStatus.SUCCESS) {
                        VodUploadResponse response = new VodUploadResponse();
                        response.setFileId(task.getFileId());
                        response.setMediaUrl(task.getMediaUrl());
                        response.setCoverUrl(task.getCoverUrl());
                        saveVideoInfo(vId,response, title, description);
                        log.info("2视频id是: {}", vId);
                    }
                } catch (Exception e) {
                    log.error("异步保存视频信息失败: {}", taskId, e);
                }
            });

            return taskId;
        } catch (Exception e) {
            log.error("提交异步上传任务失败", e);
            throw new RuntimeException("提交上传任务失败: " + e.getMessage());
        }
    }

    /**
     * 等待上传完成
     */
    private void waitForUploadCompletion(String taskId) throws InterruptedException {
        int maxWaitTime = 30 * 60 * 1000; // 30分钟超时
        int checkInterval = 2000; // 2秒检查一次

        long startTime = System.currentTimeMillis();
        while (System.currentTimeMillis() - startTime < maxWaitTime) {
            AsyncVideoUploadManager.UploadTask task = asyncUploadManager.getTaskStatus(taskId);
            if (task.getStatus() == AsyncVideoUploadManager.UploadTask.UploadStatus.SUCCESS ||
                    task.getStatus() == AsyncVideoUploadManager.UploadTask.UploadStatus.FAILED) {
                return;
            }
            Thread.sleep(checkInterval);
        }
        throw new RuntimeException("上传超时");
    }

    /**
     * 获取上传任务状态
     */
    public AsyncVideoUploadManager.UploadTask getUploadTaskStatus(String taskId) {
        return asyncUploadManager.getTaskStatus(taskId);
    }

    @Override
    public boolean updateVideo(UpdateVideoDTO updateVideoDTO) {
               Video video = this.getById(updateVideoDTO.getId());
               video.setTitle(updateVideoDTO.getTitle());
               video.setDescription(updateVideoDTO.getDescription());
               return this.updateById(video);
    }
    @Override
    public Object updateIsUse(UpdateVideoStatusBO updateVideoStatusBO) {
        // 直接使用String类型的ID
        String id = updateVideoStatusBO.getId();
        log.info("id:{}",id);
        Byte status = updateVideoStatusBO.getStatus();

        // 根据String类型的ID查询视频
        // 注意：这里需要确保Video实体类和数据库的ID字段也支持大数值
        Video video = this.getById(id);
        if (video == null) {
            throw new RuntimeException("视频不存在");
        }

        video.setStatus(status);
        return this.updateById(video);
    }

    @Override
    public IPage<Video> findPage(FindVPageDTO findVPageDTO) {
        // 创建分页对象
        Page<Video> page = new Page<>(findVPageDTO.getCurrent(), findVPageDTO.getSize());

        // 创建查询条件
        LambdaQueryWrapper<Video> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(findVPageDTO.getTitle() != null, Video::getTitle, findVPageDTO.getTitle());
        //wrapper.eq(Video::getStatus, 1);
        // 执行分页查询
        return this.page(page, wrapper);
    }

    @Override
    public Object getVideoInfoById(String id) {
        Video video = this.getById(id);
        Integer viewCount = video.getViewCount();
        log.info("当前视频的浏览次数是: {}", viewCount);
        video.setViewCount(viewCount + 1);
        this.updateById(video);
        if (video == null){
            return new RuntimeException("视频不存在");
        }
        return video;
    }

    /*
 获取浏览量为前六的视频
  */
    @Override
    public List<Video> getTop() {
        return this.baseMapper.getTopSix();
    }


    /**
     * 保存视频信息到数据库
     */
    private void saveVideoInfo(Long vId,VodUploadResponse response, String title, String description) {
        Video video = this.getById(vId);
        video.setVideoUrl(response.getMediaUrl());
        video.setCoverImage(response.getCoverUrl());
        video.setTitle(title);
        video.setDescription(description);
        this.updateById(video);
    }
    private Long saveVideoInfo(Video video, String title, String description) {
        video.setTitle(title);
        video.setDescription(description);
        video.setVideoUrl("");
        video.setCoverImage("");
        this.save(video);
        return video.getId();
    }
}
